<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Home\Controller;

use Think\Model;

/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
header('content-type:text/html;charset=utf8');

class XcxPayNoticeController extends HomeController
{
	/**
	 * 商城支付回调
	 * */
	public function goodsNotice()
	{
		$notice_info = json_decode(file_get_contents('php://input'), true);

		$order_sn = $notice_info['out_trade_no'];

		$order_info = M('order')->where(array('pay_order_sn' => $order_sn))->find();
		if ($order_info['is_pay'] == 0) {
			$data = array(
				'status' => 1,
				'is_pay' => 1,
				'pay_time' => time(),
				'update_time' => time()
			);
			M('order')->where(array('pay_order_sn' => $order_sn))->save($data);

			$goods_list = M('vice_order')->field('to_id,spec,count')->where(array('order_id' => $order_info['id']))->select();
			if ($goods_list) {
				foreach ($goods_list as &$v) {
					//增加商品销量
					M('goods')->where(array('id' => $v['to_id']))->setInc('sales_count', $v['count']);

					//减商品库存
					M('goods_spec')->where(array('goods_id' => $v['to_id'], 'spec' => $v['spec']))->setDec('count', $v['count']);
				}
			}

			//删除购物车数据
			if ($order_info['car_ids']) M('goods_car')->where(array('id' => array('IN', $order_info['car_ids'])))->delete();

			echo 'SUCCESS';
		}
	}

	/**
	 * 商品取消支付退款回调
	 * */
	public function goodsRefundNotice()
	{

		$notice_info = json_decode(file_get_contents('php://input'), true);

		$back_order_sn = $notice_info['out_refund_no'];

		$order_info = M('order')->where(array('back_order_sn' => $back_order_sn))->find();
		if($order_info['status'] == 7){
			$order_info = M('order')->where(array('back_order_sn' => $back_order_sn))->find();

			if ($order_info['status'] == 7) {
				M('order')->where(array('back_order_sn' => $back_order_sn))->save(array('status' => 8, 'update_time' => time()));

				M('order_share_price')->where(array('order_id' => $order_info['id']))->setField('status', 3);
			}

			echo 'SUCCESS';
		}
	}

	/**
	 * 直播课支付回调
	 * */
	public function liveNotice()
	{
		$notice_info = json_decode(file_get_contents('php://input'), true);

		$order_sn = $notice_info['out_trade_no'];

		$order_info = M('order')->where(array('pay_order_sn' => $order_sn))->find();
		if ($order_info['is_pay'] == 0) {
			$time = time();

			//修改订单信息
			$order_data = array(
				'is_pay' => 1,
				'pay_time' => $time,
				'update_time' => $time
			);
			M('order')->where(array('pay_order_sn' => $order_sn))->save($order_data);

			$vice_order_info = M('vice_order')->where(array('order_id' => $order_info['id']))->find();
			//增加报名人数
			M('live_course')->where(array('id' => $vice_order_info['to_id']))->setInc('enlist_count');

			$signup_ranking_data = array(
				'iid' => $order_info['iid'],
				'live' => 1,
				'order_id' => $order_info['id'],
				'create_time' => time()
			);
			M('signup_ranking')->add($signup_ranking_data);

			//将用户优惠券修改为已使用状态
			if ($order_info['user_coupon_id'] > 0) M('user_coupon')->where(array('id' => $order_info['user_coupon_id']))->setField('status', 1);

			//团购下单
			if ($order_info['group_join_id'] > 0) {
				M('group_join')->where(array('id' => $order_info['group_join_id']))->setField('status', 1);

				$group_join_info = M('group_join')->where(array('id' => $order_info['group_join_id']))->find();
				if ($group_join_info && $group_join_info['pid'] > 0) {
					//拼团信息
					$group_work_info = M('group_work')->where(array('id' => $group_join_info['gid']))->find();

					//某团的团员人数
					$son_group_count = M('group_join')->where(array('pid' => $group_join_info['pid']))->count();
					//某团的总人数
					$group_count = $son_group_count + 1;

					if ($group_work_info['people_number'] <= $group_count) {
						//拼团成功

						$map['id'] = $group_join_info['pid'];
						$map['pid'] = $group_join_info['pid'];
						$map['_logic'] = 'OR';

						$data = array(
							'status' => 2,
							'update_time' => time()
						);
						M('group_join')->where($map)->save($data);

						//当前成功的拼团总数
						$success_count = M('group_join')->where(array('gid' => $group_join_info['gid'], 'pid' => 0, 'status' => 2))->count();
						if ($success_count >= $group_work_info['group_limit_number']) {
							//所有的拼团已完成
							$up_data = array(
								'status' => 2,
								'update_time' => time()
							);
							M('group_work')->where(array('id' => $group_join_info['gid']))->save($up_data);

							//课程活动信息修改成无活动
							M('live_course')->where(array('id' => $vice_order_info['to_id']))->setField('is_activity', 0);
						}
					}
				}
			}

			//秒杀下单
			if ($order_info['skill_log_id'] > 0) {
				$skill_id = getDbFieldValue('seckill_log', array('id' => $order_info['skill_log_id']), 'seckill_id');

				if ($skill_id) {
					$skill_info = M('seckill')->where(array('id' => $skill_id))->find();

					//查询当前秒杀的数量
					$skill_count = M('seckill_log')->where(array('seckill_id' => $skill_id, 'status' => 1))->count();

					M('order')->where(array('id' => $order_info['id']))->setField('video_status', 1);
					M('seckill_log')->where(array('id' => $order_info['skill_log_id']))->setField('status', 1);

					if ($skill_count >= $skill_info['count']) {
						//秒杀完成
						M('seckill')->where(array('id' => $skill_id))->setField('status', 2);
						//课程活动信息修改成无活动
						M('live_course')->where(array('id' => $vice_order_info['to_id']))->setField('is_activity', 0);
					}
				}
			}

			echo 'SUCCESS';
		}
	}

	/**
	 * 面授课支付回调
	 * */
	public function faceNotice()
	{
		$notice_info = json_decode(file_get_contents('php://input'), true);

		$order_sn = $notice_info['out_trade_no'];

		$order_info = M('order')->where(array('pay_order_sn' => $order_sn))->find();
		if ($order_info['is_pay'] == 0) {
			$time = time();

			//修改订单信息
			$order_data = array(
				'is_pay' => 1,
				'pay_time' => $time,
				'update_time' => $time
			);
			M('order')->where(array('pay_order_sn' => $order_sn))->save($order_data);

			$vice_order_info = M('vice_order')->where(array('order_id' => $order_info['id']))->find();
			//增加报名人数
			M('face_course')->where(array('id' => $vice_order_info['to_id']))->setInc('enlist_count');

			$signup_ranking_data = array(
				'iid' => $order_info['iid'],
				'face' => 1,
				'order_id' => $order_info['id'],
				'create_time' => time()
			);
			M('signup_ranking')->add($signup_ranking_data);

			//将用户优惠券修改为已使用状态
			if ($order_info['user_coupon_id'] > 0) M('user_coupon')->where(array('id' => $order_info['user_coupon_id']))->setField('status', 1);

			//团购下单
			if ($order_info['group_join_id'] > 0) {
				M('group_join')->where(array('id' => $order_info['group_join_id']))->setField('status', 1);

				$group_join_info = M('group_join')->where(array('id' => $order_info['group_join_id']))->find();
				if ($group_join_info && $group_join_info['pid'] > 0) {
					//拼团信息
					$group_work_info = M('group_work')->where(array('id' => $group_join_info['gid']))->find();

					//某团的团员人数
					$son_group_count = M('group_join')->where(array('pid' => $group_join_info['pid']))->count();
					//某团的总人数
					$group_count = $son_group_count + 1;

					if ($group_work_info['people_number'] <= $group_count) {
						//拼团成功

						$map['id'] = $group_join_info['pid'];
						$map['pid'] = $group_join_info['pid'];
						$map['_logic'] = 'OR';

						$data = array(
							'status' => 2,
							'update_time' => time()
						);
						M('group_join')->where($map)->save($data);

						//当前成功的拼团总数
						$success_count = M('group_join')->where(array('gid' => $group_join_info['gid'], 'pid' => 0, 'status' => 2))->count();
						if ($success_count >= $group_work_info['group_limit_number']) {
							//所有的拼团已完成
							$up_data = array(
								'status' => 2,
								'update_time' => time()
							);
							M('group_work')->where(array('id' => $group_join_info['gid']))->save($up_data);

							//课程活动信息修改成无活动
							M('face_course')->where(array('id' => $vice_order_info['to_id']))->setField('is_activity', 0);
						}
					}
				}
			}

			//秒杀下单
			if ($order_info['skill_log_id'] > 0) {
				$skill_id = getDbFieldValue('seckill_log', array('id' => $order_info['skill_log_id']), 'seckill_id');

				if ($skill_id) {
					$skill_info = M('seckill')->where(array('id' => $skill_id))->find();

					//查询当前秒杀的数量
					$skill_count = M('seckill_log')->where(array('seckill_id' => $skill_id, 'status' => 1))->count();

					M('order')->where(array('id' => $order_info['id']))->setField('video_status', 1);
					M('seckill_log')->where(array('id' => $order_info['skill_log_id']))->setField('status', 1);

					if ($skill_count >= $skill_info['count']) {
						//秒杀完成
						M('seckill')->where(array('id' => $skill_id))->setField('status', 2);
						//课程活动信息修改成无活动
						M('face_course')->where(array('id' => $vice_order_info['to_id']))->setField('is_activity', 0);
					}
				}
			}

			echo 'SUCCESS';
		}
	}

	/**
	 * 点播课支付回调
	 * */
	public function videoNotice()
	{
		$notice_info = json_decode(file_get_contents('php://input'), true);

		$order_sn = $notice_info['out_trade_no'];

		$order_list = M('order')->where(array('pay_order_sn' => $order_sn))->select();
		if ($order_list[0]['is_pay'] == 0) {
			$time = time();

			foreach ($order_list as &$v) {
				//修改订单信息
				$order_data = array(
					'is_pay' => 1,
					'pay_time' => $time,
					'update_time' => $time
				);
				if ($v['type'] == 4) {
					//商品
					$order_data['status'] = 1;
					M('order')->where(array('id' => $v['id']))->save($order_data);

					$goods_list = M('vice_order')->field('to_id,spec,count')->where(array('order_id' => $v['id']))->select();
					if ($goods_list) {
						foreach ($goods_list as &$val) {
							$goods_id = M('video_book')->where(array('id' => $val['to_id']))->getField('goods_id');
							if ($goods_id) {
								//增加商品销量
								M('goods')->where(array('id' => $goods_id))->setInc('sales_count', $val['count']);
								//减商品库存
								M('goods_spec')->where(array('goods_id' => $val['to_id'], 'spec' => $val['spec']))->setDec('count', $val['count']);
							}

							//增加在线课绑定书籍销量
							M('video_book')->where(array('id' => $val['to_id']))->setInc('sales_count');
						}
					}
				} else {
					//在线课
					$order_data['video_status'] = 1;

					M('order')->where(array('id' => $v['id']))->save($order_data);

					$vice_order_info = M('vice_order')->where(array('order_id' => $v['id']))->find();
					//增加销量
					M('video_course')->where(array('id' => $vice_order_info['to_id']))->setInc('sales_count');


					$signup_ranking_data = array(
						'iid' => $v['iid'],
						'video' => 1,
						'order_id' => $v['id'],
						'create_time' => time()
					);
					M('signup_ranking')->add($signup_ranking_data);

					//将用户优惠券修改为已使用状态
					if ($v['user_coupon_id'] > 0) M('user_coupon')->where(array('id' => $v['user_coupon_id']))->setField('status', 1);

					//团购下单
					if ($v['group_join_id'] > 0) {
						M('group_join')->where(array('id' => $v['group_join_id']))->setField('status', 1);

						$group_join_info = M('group_join')->where(array('id' => $v['group_join_id']))->find();
						if ($group_join_info) {
							if ($group_join_info['pid'] > 0) {
								//用户参与拼团

								//拼团信息
								$group_work_info = M('group_work')->where(array('id' => $group_join_info['gid']))->find();

								//某团的团员人数
								$son_group_count = M('group_join')->where(array('pid' => $group_join_info['pid']))->count();
								//某团的总人数
								$group_count = $son_group_count + 1;

								if ($group_work_info['people_number'] <= $group_count) {
									//拼团成功

									$map['id'] = $group_join_info['pid'];
									$map['pid'] = $group_join_info['pid'];
									$map['_logic'] = 'OR';

									$data = array(
										'status' => 2,
										'update_time' => time()
									);
									M('group_join')->where($map)->save($data);

									M('order')->where(array('id' => $v['id']))->setField('video_status', 1);

									$success_list = M('group_join')->where($map)->select();
									if ($success_list) {
										foreach ($success_list as &$val) {
											//用户点播课程处理
											$this->doUserVideoCourse($group_work_info['course_id'], $val['uid']);
										}
									}

									//当前成功的拼团总数
									$success_count = M('group_join')->where(array('gid' => $group_join_info['gid'], 'pid' => 0))->count();
									if ($success_count >= $group_work_info['group_limit_number']) {
										//所有的拼团已完成
										$up_data = array(
											'status' => 2,
											'update_time' => time()
										);
										M('group_work')->where(array('id' => $group_join_info['gid']))->save($up_data);

										//课程活动信息修改成无活动
										M('video_course')->where(array('id' => $vice_order_info['to_id']))->setField('is_activity', 0);
									}
								}
							} else {
								//用户发起拼团，添加结束执行的redis记录到集合
								$redisCtr = A('Home', 'Redis');
								$group_work_info = M('group_work')->where(array('id' => $group_join_info['id']))->find();
								$task_param = array(
									'category' => 2,
									'group_work_id' => $group_work_info['id'],
								);
								//添加结束执行的redis记录到集合
								$end_time = time() + $group_work_info['time_limit'] * 60;
								$redisCtr->addRedis('chiefEnd', $end_time, $task_param);
							}
						}
					} else {
						//用户点播课程处理
						$this->doUserVideoCourse($vice_order_info['to_id'], $v['uid']);

						//秒杀下单
						if ($v['skill_log_id'] > 0) {
							$skill_id = getDbFieldValue('seckill_log', array('id' => $v['skill_log_id']), 'seckill_id');

							if ($skill_id) {
								$skill_info = M('seckill')->where(array('id' => $skill_id))->find();

								//查询当前秒杀的数量
								$skill_count = M('seckill_log')->where(array('seckill_id' => $skill_id, 'status' => 1))->count();

								M('order')->where(array('id' => $v['id']))->setField('video_status', 1);
								M('seckill_log')->where(array('id' => $v['skill_log_id']))->setField('status', 1);

								if ($skill_count >= $skill_info['count']) {
									//秒杀完成
									M('seckill')->where(array('id' => $skill_id))->setField('status', 2);
									//课程活动信息修改成无活动
									M('video_course')->where(array('id' => $vice_order_info['to_id']))->setField('is_activity', 0);
								}
							}
						}
					}
				}
			}

			echo 'SUCCESS';
		}
	}

	/**
	 * 用户点播课程处理
	 * @param        int        $id         课程id
	 * @param        int        $uid        用户id
	 * */
	public function doUserVideoCourse($id, $uid)
	{
		//为用户增加课程
		$video_course_info = M('video_course')->where(array('id' => $id))->find();
		$user_video_course_info = M('user_video_course')->where(array('uid' => $uid, 'vc_id' => $id))->find();

		//用户点播课程入库
		if ($user_video_course_info) {
			//修改
			if ($video_course_info['buy_expire_day'] == 0) {
				//永久有效
				$up_user_video_course_data = array(
					'look_auth' => 1,
					'expire_time' => 0,
					'update_time' => time()
				);
				M('user_video_course')->where(array('uid' => $uid, 'vc_id' => $id))->save($up_user_video_course_data);
			} else {
				//有过期时间
				if ($user_video_course_info['expire_time'] > time()) {
					$expire_time = $user_video_course_info['expire_time'] + 3600 * 24 * $video_course_info['buy_expire_day'];
				} else {
					$expire_time = time() + 3600 * 24 * $video_course_info['buy_expire_day'];
				}

				$up_user_video_course_data = array(
					'look_auth' => 1,
					'expire_time' => $expire_time,
					'update_time' => time()
				);
				M('user_video_course')->where(array('uid' => $uid, 'vc_id' => $id))->save($up_user_video_course_data);
			}
		} else {
			//新增
			$expire_time = ($video_course_info['buy_expire_day'] == 0) ? 0 : time() + 3600 * 24 * $video_course_info['buy_expire_day'];
			$add_user_video_course_data = array(
				'uid' => $uid,
				'vc_id' => $id,
				'look_auth' => 1,
				'expire_time' => $expire_time,
				'create_time' => time()
			);
			M('user_video_course')->add($add_user_video_course_data);
		}
	}

	/**
	 * 影印资料上传审核结果通知（手持身份证）
	 * 机构端：
	 *      小程序上传身份证正反面，手持身份证照片（jpg,png），小于200KB
	 *      总后台审核通过时调用【小B商户进件】等第三方接口去申请审核
	 *      审核通过之后，在该回调中调用【添加分账方】接口，机构状态修改为已审核通过状态
	 * 供应商端：
	 *      总后台添加供应商，上传身份证正反面，手持身份证照片（jpg,png），小于200KB
	 *      总后台审核通过时调用【小B商户进件】等第三方接口去申请审核
	 *      审核通过之后，在该回调中调用【添加分账方】接口，供应商状态修改为已审核通过状态
	 * */
	public function infoNotice()
	{
		$notice_info = json_decode(file_get_contents('php://input'), true);
		file_put_contents(RUNTIME_PATH . 'infoNoticeSupplier123.txt', $notice_info['sub_mch_code']);
		//$notice_info = json_decode($notice_info, true);

		//file_put_contents(RUNTIME_PATH . 'infoNoticeSupplier.txt', json_encode($notice_info));

		$sub_mch_code = $notice_info['sub_mch_code'];

		$institution_info = M('institution')->where(array('sub_mch_code' => $sub_mch_code))->find();
		if($institution_info){
			$receiver = array(
				'name' => $institution_info['username'],
				'type' => 1,
				'account' => $sub_mch_code
			);
			$db = M('institution');
		}

		$supplier_info = M('supplier')->where(array('sub_mch_code' => $sub_mch_code))->find();
		if($supplier_info){
			$receiver = array(
				'name' => $supplier_info['name'],
				'type' => 1,
				'account' => $sub_mch_code
			);
			$db = M('supplier');
		}

		Vendor('pay.pay');
		$data['receiver'] = json_encode($receiver);

		$obj = new \pay($data);
		$result = $obj->receivers();
		if($result['data']['result_code'] == 'SUCCESS'){
			$up_data = array(
				'api_status' => 1,
				'update_time' => time()
			);
			$res = $db->where(array('sub_mch_code' => $sub_mch_code))->save($up_data);
			echo 'SUCCESS';
		}
	}
    public function notice(){
        $notice_info = file_get_contents("php://input");
        $notice_info = json_decode($notice_info, true);
		$state=$notice_info['state'];
        if($state==00){
        	//支付成功
        	$out_trade_no=$notice_info['out_trade_no'];//订单号
        	$info=M('order')->where("order_sn=$out_trade_no")->find();
        	if($notice_info['product']='WECHAT_LITE'){
        		//微信支付
        		$data['pay_type']=1;
        	}else{
        		//支付宝支付
        		$data['pay_type']=2;
        	}
        	$data['is_pay']=1;
        	$data['status']=4;
        	$res=M('order')->where("order_sn=$out_trade_no")->save($data);
        	//购买成功之后 我还要插数据到报名排行表
        	if($res){
        		$add_data['iid']=$info['iid'];
        		$add_data['order_id']=$info['id'];
        		$add_data['create_time']=time();

        		if($info['type']==1){
        			//直播课
        			$add_data['live']=1;
        		}elseif($info['type']==2){
        			//面授课
        			$add_data['face']=1;
        		}else{
        			//在线  点播
        			$add_data['video']=1;
        		}
        		M('signup_ranking')->add($add_data);
        	}
        }
    }
}